package com.woniuxy.dudugua.service.impl;

import com.woniuxy.dudugua.entity.*;
import com.woniuxy.dudugua.exception.UnderstockException;
import com.woniuxy.dudugua.mapper.OrderInfoMapper;
import com.woniuxy.dudugua.mapper.OrderMapper;
import com.woniuxy.dudugua.mapper.ProductMapper;
import com.woniuxy.dudugua.mapper.ProductSkuMapper;
import com.woniuxy.dudugua.service.OrderService;
import com.woniuxy.dudugua.util.view.ProductAndCategoryView;
import com.woniuxy.dudugua.util.view.UserCouponsView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

@Service
public class OrderServiceImpl implements OrderService {
    @Resource
    private OrderMapper orderMapper;
    @Resource
    private ProductSkuMapper productSkuMapper;
    @Resource
    private OrderInfoMapper orderInfoMapper;
    @Autowired
    private ProductMapper productMapper;
    @Override
    public List<UserCouponsView> selectUserConponsViewCanUse(int userid, Integer[] skuid) {
        List<UserCouponsView> couponsList = orderMapper.selectCouponsView(userid);
        List<ProductAndCategoryView> productList = new ArrayList();
        for (int i = 0; i < skuid.length; i++) {
            ProductAndCategoryView view = selectProductAndCategoryViewBySkuId(skuid[i]);
            productList.add(view);
        }
        Map<Integer,UserCouponsView> map = new HashMap();
        for(int i = 0;i < couponsList.size();i++){
            boolean b = false;
            for(int j = 0;j < productList.size();j++){
                b = canUse(couponsList.get(i), productList.get(j));
                if(b) break;
            }
            if(b) map.put(couponsList.get(i).getUserCouponsId(),couponsList.get(i));
        }
        List<UserCouponsView> list = new ArrayList();
        Set<Integer> integers = map.keySet();
        Iterator<Integer> it = integers.iterator();
        while(it.hasNext()){
            UserCouponsView userCouponsView = map.get(it.next());
            list.add(userCouponsView);
        }
        return list;
    }
    //判断是否能够使用优惠券
    public boolean canUse(UserCouponsView userCouponsView, ProductAndCategoryView productAndCategoryView){
        if(userCouponsView.getUseScope() == 1 && userCouponsView.getUseType() == 0) return true;
        if(userCouponsView.getUseScope() == 2){
            if(productAndCategoryView.getStoreid() != userCouponsView.getScopeId()){
                return false;
            }
            if(userCouponsView.getUseType() != 0 && productAndCategoryView.getCategoryid() != userCouponsView.getUseType()){
                return false;
            }
        }
        if(userCouponsView.getUseScope() == 3){
            if(productAndCategoryView.getPid() != userCouponsView.getScopeId()){
                return false;
            }
        }
        if(userCouponsView.getUseScope() == 2 && userCouponsView.getUseType() != 0){
            if(productAndCategoryView.getStoreid() != userCouponsView.getScopeId() || productAndCategoryView.getCategoryid() != userCouponsView.getUseType()){
                return false;
            }
        }
        if(userCouponsView.getUseType() != 0){
            if(productAndCategoryView.getCategoryid() != userCouponsView.getUseType()) return false;
        }
        return true;
    }

    @Override
    public ProductAndCategoryView selectProductAndCategoryViewBySkuId(int skuid) {
        List<ProductAndCategoryView> p = orderMapper.selectProductCategoryViewBySkuID(skuid);
        return p.get(0);
    }
    //修改增加销量
    private int  addStock(List<OrderInfo> list){
        for(int i = 0;i < list.size();i++){
            OrderInfo orderInfo = list.get(i);
            ProductSku productSku = productSkuMapper.selectByPrimaryKey(orderInfo.getProductSkuId());
            Integer productId = productSku.getProductId();
            Product product = productMapper.selectByPrimaryKey(productId);
            product.setSales(product.getSales() + orderInfo.getNumber());
            int i1 = productMapper.updateByPrimaryKey(product);
        }
        return 1;
    }

    @Override
    public synchronized int insertOrder(List<OrderInfo> list, Address address, UserCouponsView userCouponsView,int userid) {
        //创建订单
        double total = componentTotal(list);
        Order order = new Order();
        order.setStatus(1);
        order.setCouponId(userCouponsView == null ? 0 : userCouponsView.getUserCouponsId());
        order.setAddress(address.getAddress() + address.getArea() +","+ address.getMobile() + "," + address.getName());
        order.setTotal(total - (userCouponsView == null? 0:userCouponsView.getSale()));
        order.setAddTime(new Date());
        order.setUserId(userid);
        int insert = orderMapper.insert(order);
        //创建orderinfo
        int orderinfo = createOrderinfo(list, userCouponsView, order.getId());
        addStock(list);
        return order.getId();
    }

    @Override
    public Order selectOrderById(int id) {
        Order order = orderMapper.selectByPrimaryKey(id);
        return order;
    }
    //1为付款成功 2为订单已取消  3为订单已付款
    @Override
    public int updateStatus(int orderid, int status) {
        Order order = orderMapper.selectByPrimaryKey(orderid);
        if(order.getStatus() == 1){
            order.setStatus(status);
            orderMapper.updateByPrimaryKey(order);
        }else if(order.getStatus() == 5){
            return 2;
        }else{
            return 3;
        }
        return 1;
    }

    @Override
    public List<UserCouponsView> selectAllConpons(Integer userId) throws Exception {
        return orderMapper.selectCouponsView(userId);
    }

    //计算订单info总价
    private double componentTotal(List<OrderInfo> list){
        double total = 0.0;
        for(OrderInfo o : list){
            total = o.getMoney() + total;
        }
        return total;
    }

    //下单减库存
    private int InventoryReduction(OrderInfo orderInfo) throws UnderstockException {
        ProductSku sku = productSkuMapper.selectByPrimaryKey(orderInfo.getProductSkuId());
        if(orderInfo.getNumber() > sku.getNumber()){
            throw new UnderstockException();
        }
        sku.setNumber(sku.getNumber() - orderInfo.getNumber());
        int i = productSkuMapper.updateByPrimaryKey(sku);
        return i;
    }

    private int createOrderinfo(List<OrderInfo> list,UserCouponsView userCouponsView,int orderid){
        if(userCouponsView == null){
            for(int i = 0;i < list.size();i++){
                OrderInfo orderInfo = list.get(i);
                orderInfo.setOrderId(orderid);
                int insert = orderInfoMapper.insert(orderInfo);
            }
            return 1;
        }
        //获取视图对象
        List<ProductAndCategoryView> productList = new ArrayList();
        for (int i = 0; i < list.size(); i++) {
            ProductAndCategoryView view = selectProductAndCategoryViewBySkuId(list.get(i).getProductSkuId());
            productList.add(view);
        }
        //进行比较
        List<ProductAndCategoryView> list1 = new ArrayList();
        List<ProductAndCategoryView> list2 = new ArrayList();
        for (int i = 0;i < productList.size();i ++){
            boolean b = canUse(userCouponsView,productList.get(i));
            if(b){ list1.add(productList.get(i));}
            else {list2.add(productList.get(i));}
        }
        List<OrderInfo> canUse = new ArrayList();
        List<OrderInfo> cantUse = new ArrayList();
        for(int i = 0;i < list1.size();i++ ){
            if(list.get(i).getProductSkuId() == list1.get(i).getSkuid()){
                canUse.add(list.get(i));
            }
        }
        for(int i = 0;i < list2.size();i++ ){
            if(list.get(i).getProductSkuId() != list1.get(i).getSkuid()){
                cantUse.add(list.get(i));
            }
        }
        //创建orderinfo  可以使用优惠券的订单
       for(int i = 0;i < canUse.size();i++){
           OrderInfo orderInfo = canUse.get(i);
           orderInfo.setOrderId(orderid);
           orderInfo.setMoney(orderInfo.getMoney() - userCouponsView.getSale()/canUse.size());
           int insert = orderInfoMapper.insert(orderInfo);
       }
       //不可以使用优惠券的
        for(int i = 0;i < cantUse.size();i++){
            OrderInfo orderInfo = cantUse.get(i);
            orderInfo.setOrderId(orderid);
            int insert = orderInfoMapper.insert(orderInfo);
        }
        return 1;
    }


}
